/*
 * =====================================================================================
 *
 *       Filename:  main.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  02/17/12 16:13:14
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  randyli (randy), randyli@tencent.com
 *        Company:  Tencent
 *
 * =====================================================================================
 */

#include <memory.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <unistd.h>
#include "compiler.h"
#include "array.h"

setting settings;

int settings_init()
{
	settings.dump_opcode = 0;
	return 0;
}

int usage()
{
	printf("./smt <options> <source file>\n");
	printf(" -d dump opcodes\n");
	return 0;
}

int main(int argc, char* argv[])
{
	
		
	int i,c, rlen;
	scompiler* s;
	svm* vm;
	exe e;
	char* sfile;	
	char buf[1024*1024];
	FILE* fp;
	while ((c = getopt(argc, argv, "dh")) != -1) {
		switch (c) {
			case 'd': 
				settings.dump_opcode = 1; 
				break;
			case 'h':
				usage();
				exit(0);
			default:     
				fprintf(stderr, "Illegal argument \"%c\"\n", c);
				return 1;
		}
	}
	if(argc == optind)
	{
		usage();exit(0);
	}
	sfile = argv[optind];
	
	fp = fopen(sfile, "r");
	if(!fp){
		printf("%s does not exists\n", sfile);
		return -1;
	}
	rlen = fread(buf, 1, 1024*1024, fp);
	if(rlen < 0){
		printf("read source file error\n", sfile);
		return -1;
	}
	buf[rlen] = 0;
	compiler_init(&s);
	compile_str(s, buf, strlen(buf));
	
	if(settings.dump_opcode)
	{
		for(i=0;i<s->sconst_pos;i++)
		{
			printf("%c", s->sconst[i]);
		}
		op_dump(s->ops, s->ops_num);
	}
	svm_new(&vm);
	e.ops = s->ops;
	e.ops_num = s->ops_num;
	e.start = 0;
	e.sconst = s->sconst;
	
	e.ntmp =  s->st->length;
	
	smt_array* g;
	smt_array_new(&g);
	object data[10];
	for(i=0;i<10;i++)
	{
		data[i].type = INT;
		ivalue(data[i]) = i;
		smt_array_set(g,"",0, data + i);
	}
	ovalue(vm->stack[1]) = g;
	typeof(vm->stack[1]) = ARRAY;
	svm_run(vm, &e);
}

